﻿using CIS.Common.Dtos.ClientDtos;
using CIS.Common.Entitys;
using CIS.Server.Common.Responses;
using CIS.Server.Manager.Job;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net;
using System.Reflection.Metadata;

namespace CIS.Server.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class JobController : ControllerBase
    {
        private readonly IJobManager _jobManager;
        private readonly ILogger logger;

        public JobController(IJobManager jobManager,ILogger logger)
        {
            this._jobManager = jobManager;
            this.logger = logger;
        }

        [HttpGet]
        public async Task<ResponseResult> GetJobs()
        {
            ResponseResult response = new ResponseResult();
            try
            {
                List<JobEntity> jobs = await _jobManager.GetAllJobsAsync();
                if (jobs != null && jobs.Count > 0)
                {
                    jobs = jobs.OrderBy(p => p.SlotSequenceNo).ToList();
                    response.IsSuccess = true;
                    response.StatusCode = HttpStatusCode.OK;
                    response.Message = "Operation Is Success";
                    response.Data = jobs;
                }
                else
                {
                    response.IsSuccess = false;
                    response.StatusCode = HttpStatusCode.OK;
                    response.Message = "Operation Is Failed Because Can't Find Any Port";
                }
                return response;
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Message = "Operation Is Failed Because Server Is Error";
                return response;
            }
        }

        [HttpGet]
        public async Task<ResponseResult> GetJobsByPortId(string portId)
        {
            ResponseResult response = new ResponseResult();
            try
            {
                if (string.IsNullOrWhiteSpace(portId))
                {
                    List<JobEntity> jobs = await _jobManager.GetJobsByPortIdAsync(portId);
                    if (jobs != null && jobs.Count > 0)
                    {
                        jobs = jobs.OrderBy(p => p.SlotSequenceNo).ToList();
                        response.IsSuccess = true;
                        response.StatusCode = HttpStatusCode.OK;
                        response.Message = "Operation Is Success";
                        response.Data = jobs;
                    }
                    else
                    {
                        response.IsSuccess = false;
                        response.StatusCode = HttpStatusCode.OK;
                        response.Message = "Operation Is Failed Because Can't Find Any Port";
                    }
                }                
                return response;
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Message = "Operation Is Failed Because Server Is Error";
                return response;
            }
        }

        [HttpGet]
        public async Task<ResponseResult> AddJobs([FromBody] string parameter)
        {
            ResponseResult response = new ResponseResult();
            try
            {
                CassetteMapDownLoadClientDto? dto = JsonConvert.DeserializeObject<CassetteMapDownLoadClientDto>(parameter);
                var jobs =await _jobManager.GetJobsByPortIdAsync(dto?.PortId);
                if (dto != null && dto.JobInfos.Count > 0)
                {
                    List<JobEntity> updateJobs = new List<JobEntity>();
                    List<JobEntity> AddJobs = new List<JobEntity>();
                    foreach(var item in dto.JobInfos)
                    {
                        var job = jobs.Find(j => j.JobId == item.JobId);
                        if (job != null && item != null)
                        {
                            job.PPID = item.PPID;
                            job.Judge = item.Judge;
                            job.Grade = item.Grade;
                            job.Status = item.Status;
                            job.ProductType = item.ProductType;
                            job.SlotState = item.SlotState;
                            job.Thickness = item.Thickness;
                            job.WorkOrder = item.WorkOrder;
                            updateJobs.Add(job);
                        }
                        else
                        {
                            JobEntity jobEntity = new JobEntity();
                            jobEntity.LotId = item.LotId;
                            jobEntity.ProductSize = item.ProductSize;
                            jobEntity.JobId = item.JobId;
                            jobEntity.GlassType =item.GlassType.ToString();
                            jobEntity.CassetteSequenceNo =item.CassetteSequenceNo;
                            jobEntity.SlotSequenceNo =item.SlotSequenceNo;
                            jobEntity.GlassCode =item.GlassCode;
                            jobEntity.ProductCategory =item.ProductCategory;
                            jobEntity.ProductCategory =item.ProductCategory;
                            jobEntity.Judge = item.Judge;
                            jobEntity.PPID = item.PPID;
                            jobEntity.Grade = item.Grade;
                            jobEntity.Status = item.Status;
                            jobEntity.ProductType = item.ProductType;
                            jobEntity.SlotState = item.SlotState;
                            jobEntity.Thickness = item.Thickness;
                            jobEntity.WorkOrder = item.WorkOrder;
                            AddJobs.Add(jobEntity);
                        }
                    }
                    if(updateJobs.Count > 0)
                    {
                        await _jobManager.UpdateManyJobsAsync(updateJobs);
                    }
                    if(AddJobs.Count > 0)
                    {
                        await _jobManager.AddManyJobsAsync(AddJobs);
                    }
                    response.IsSuccess = true;
                    response.StatusCode = HttpStatusCode.OK;
                    response.Message = "Operation Is Success";
                    response.Data = jobs;
                }
                else
                {
                    response.IsSuccess = false;
                    response.StatusCode = HttpStatusCode.OK;
                    response.Message = "Operation Is Failed Because Can't Find Any Port";
                }
                return response;
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Message = "Operation Is Failed Because Server Is Error";
                return response;
            }
        }

    }
}
